import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms";
import { Command } from "../../../../shared/toolbar.service";
import { Observable } from "rxjs/Observable";
import { DatePipe } from '@angular/common';
import { Role } from "../../../../entity/role.model";
import { UserProfile } from "../../../../entity/user-profile.model";
import { UserFarm } from "../../../../entity/user-farm.model";
import { User, UserManage } from "../../../../entity/user.model";
import { UserService } from "../../../../service/user.service";
import { Farm } from "../../../../entity/farm.model";
import { FarmService } from "../../../../service/farm.service";
import { RoleService } from "../../../../service/role.service";
import { FactoryService } from "../../../../service/factory.service";
import { Company } from "../../../../entity/company.model";
import { ApplicationService } from "../../../../service/application.service";
@Component({
  selector: 'app-user-edit',
  templateUrl: './user-edit.component.html',
  styleUrls: ['./user-edit.component.css']
})
export class UserEditComponent extends BladeContainerBase<UserManage> {

  public companyItmes: Company[] = [];
  /**
   * 允许的风场
   * 
   * @type {UserFarm[]}
   * @memberof UserEditComponent
   */
  userFarms: UserFarm[] = [];


  /**
   * 风场
   * 
   * @type {Farm[]}
   * @memberof UserEditComponent
   */
  farms: Farm[] = [];

  /**
   * 角色
   * 
   * @type {Role[]}
   * @memberof UserEditComponent
   */
  roles: Role[] = [];


  /**
   * 确认密码 
   * 
   * @type {string}
   * @memberof UserEditComponent
   */
  confirmPasswords: string = '';


  userManage: UserManage;

  showErrow: boolean = true;

  file: File;
  localhostPath: string;
  isDisabled: boolean = true;

  constructor(
    private userService: UserService,
    private farmService: FarmService,
    private roleService: RoleService,
    private fb: FormBuilder,
    private datePipe: DatePipe,
    private factoryService: FactoryService,

  ) {
    super(fb);
  }
  private curWwwPath: string;
  private pathName: string;
  private pos: number;
  ngOnInit(): void {
    // this.localhostPath = window.location.origin;
    // this.localhostPath = this.localhostPath == 'http://localhost:4200' ? 'http://192.168.15.109:8080' : this.localhostPath;  
    this.curWwwPath = window.location.href;
    this.pathName = window.location.pathname;
    this.pos = this.curWwwPath.indexOf(this.pathName);
    this.localhostPath = this.curWwwPath.substring(0, this.pos);
    this.localhostPath = (this.localhostPath == 'http://localhost:4200')?this.localhostPath+'/assets/images':this.localhostPath+'/img';  

    //编辑时注册按钮和按钮命令    
    if (!this.isNew) {
      //编辑
      this.showErrow = false;
      this.commands = [
        new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]

    } else {
      //新建
      let sysUser = new User();
      sysUser.userId = 0;
      sysUser.userName = "",
        sysUser.passWord = "",
        sysUser.unEnabled = true,
        sysUser.dateCreated = this.datePipe.transform(new Date(), "yyyy-MM-dd HH:mm:ss"),

        sysUser.dateLastPasswordChange = "",
        sysUser.dateLastLogin = "",
        sysUser.dateLastActivity = "",
        sysUser.icon = "",
        sysUser.realName = ""
      let sysProfile = new UserProfile();
      // sysProfile.userId = 0;
      sysProfile.email = "";
      sysProfile.faxNo = "";
      sysProfile.icon = "";
      sysProfile.lastupDate = "",
        sysProfile.menuId = 1;
      sysProfile.passwordAnswer = "";
      sysProfile.passwordQuestion = "";
      sysProfile.realName = "";
      sysProfile.roleId = 1;
      sysProfile.skinId = 1;
      sysProfile.telNo = "";
      sysProfile.title = "";
      sysProfile.sex = 1;
      sysProfile.companyId = this.parentEntity.company.companyId;


      let basicUserFarmList: UserFarm[] = [];
      this.currentEntity = new UserManage(sysUser, sysProfile, basicUserFarmList);
    }
    super.ngOnInit();
    this.initData();
    this.initCompany();
  }

  /**
   * 重新构建组织结构
   * 
   * @private
   * @memberof MenuEditComponent
   */
  private initCompany() {
    this.companyItmes = [];
    let companys: Company[] = this.parentEntity.companys;
    companys.forEach(company => {
      let companyItme: Company = new Company(
        company.companyId,
        company.companyName,
        company.companyCode,
        company.enName,
        company.contact,
        company.telNo,
        company.email,
        company.faxNo,
        company.city,
        company.addr,
        company.zip,
        company.introduce,
        company.parentId,
      );
      let name = "|";
      for (let i = 0; i < company.companyLevel; i++) {
        name += "— ";
      }
      companyItme.companyName = `${name}${companyItme.companyName}`;
      this.companyItmes.push(companyItme);
    });
  }

  /**
   * 初始化数据
   * 
   * @returns {(any | Observable<any> | Promise<any>)} 
   * @memberof UserEditComponent
   */
  initData(): any | Observable<any> | Promise<any> {
    if (!this.isNew) {
      let farmsGet = this.farmService.getFarms();
      let userManageGet = this.userService.getUsersByuserId(this.currentEntity.sysUser.userId);
      let rolesGet = this.roleService.getRoles();
      Promise.all([farmsGet, userManageGet, rolesGet])
        .then(res => {
          this.farms = res[0];
          this.userManage = res[1];
          this.roles = res[2];
          this.currentEntity.basicUserFarmList = res[1].basicUserFarmList;
          this.currentEntity.sysProfile = res[1].sysProfile;
          this.currentEntity.basicUserFarmList.forEach(o => {
            let index = this.userFarms.findIndex(u => o.farmId == u.farmId);
            if (index == -1) {
              this.userFarms.push(o)
            }
          })


          this.farms.forEach(farm => {
            if (this.currentEntity.basicUserFarmList != undefined) {
              this.currentEntity.basicUserFarmList.forEach(userFarm => {
                if (farm.farmId == userFarm.farmId) {
                  farm.isChecked = true
                }
              })
            }
          })

          this.roles.forEach(role => {
            role.isChecked = this.currentEntity.sysProfile.roleId == role.roleId ? true : false;
          })

          this.formPatchValue(this.currentEntity);
        }).catch(err => {
          this.bladeData.error = err;
        })
    } else {
      let farmsGet = this.farmService.getFarms();
      let rolesGet = this.roleService.getRoles();
      Promise.all([farmsGet, rolesGet])
        .then(res => {
          this.farms = res[0];
          this.roles = res[1];
          this.formPatchValue(this.currentEntity);
        }).catch(err => {
          this.bladeData.error = err;
        })
    }


  }
  exeSaveChange(blade: any): void {
    this.saveChange();
  }
  canSaveChange(blade: any): boolean {
    return (this.hasChange() || this.file) && !this.hasError() && !this.showErrow;
  }
  exeReset(blade: any): void {
    this.refresh();
    this.file = null
    this.showErrow = false;
    return this.formGroup.reset(this.currentEntity);
  }
  canReset(blade: any): boolean {
    return (this.hasChange() || this.file ? true : false) || this.showErrow;
  }

  /**
   * 
   * 刷新 
   * @param {*} anyData 
   * @memberof UserEditComponent
   */
  refresh(): void {
    this.userFarms = [];
    this.currentEntity.basicUserFarmList.forEach(f => {
      this.userFarms.push(f)
    })
    this.currentBlade.bladeData.isLoading = false;
    this.initData();
  }

  /**
    * 是否存在变更
    * 
    * @returns {boolean} 
    * 
    * @memberof BladeContainerBase
    */
  hasChange(): boolean {
    if (this.formGroup != null) {
      let userEnity = this.formGroup.controls["sysUser"].value;
      let userEnityNames: string[] = Object.getOwnPropertyNames(userEnity);
      for (let i: number = 0; i < userEnityNames.length; i++) {
        let name = userEnityNames[i];
        if (this.currentEntity.sysUser.hasOwnProperty(name)) {
          let value = Object.getOwnPropertyDescriptor(this.currentEntity.sysUser, name).value;
          if (value != userEnity[name]) {
            return true;
          }
        }
      }

      let sysProfileEnity = this.formGroup.controls["sysProfile"].value;

      let sysProfileEnityNames: string[] = Object.getOwnPropertyNames(sysProfileEnity);
      for (let i: number = 0; i < sysProfileEnityNames.length; i++) {
        let name = sysProfileEnityNames[i];
        if (this.currentEntity.sysProfile.hasOwnProperty(name)) {
          let value = Object.getOwnPropertyDescriptor(this.currentEntity.sysProfile, name).value;
          if (value != sysProfileEnity[name]) {
            return true;
          }
        }
      }
    }

    if (this.currentEntity.basicUserFarmList != null) {
      if (this.userFarms) {
        if (this.userFarms.length != this.currentEntity.basicUserFarmList.length) {
          return true;
        } else {
          let change: boolean = false;
          this.userFarms.forEach(f => {
            if (!this.currentEntity.basicUserFarmList.find(o => o.farmId == f.farmId)) {
              change = true;
              return;
            }
          })
          return change;
        }
      } else {
        return true;
      }
    } else {
      if (!this.userFarms) {
        return false;
      }
      return true;
    }

  }
  /**
    * 创建表单
    * 
    * 
    * @memberof DicKeyEditComponent
    */
  createForm() {
    let obj: {} = {
      sysUser: this.fromBuider.group({
        "unEnabled": [this.currentEntity.sysUser.unEnabled, [
        ],],
        "userName": [this.currentEntity.sysUser.userName, [
          Validators.required,
          Validators.pattern("^[\u4e00-\u9fa5a-zA-Z0-9]+$"),
          Validators.maxLength(50),
        ], (control: FormControl): any => this.userNameAsnyValidator(control)],
        "realName": [this.currentEntity.sysUser.realName, [
          Validators.required,
          Validators.maxLength(50),
        ],],
        "passWord": [this.currentEntity.sysUser.passWord, [
          Validators.required,
          Validators.maxLength(50),
        ],],
      }),
      sysProfile: this.fromBuider.group({
        "email": [this.currentEntity.sysProfile.email, [
          Validators.pattern("^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$"),
          Validators.maxLength(20),
        ],],
        "telNo": [this.currentEntity.sysProfile.telNo, [
          Validators.pattern("^(1)([3,4,5,7,8])([0-9]{9})$"),
          Validators.maxLength(11),
        ],],
        "faxNo": [this.currentEntity.sysProfile.faxNo, [
          Validators.pattern("^([0-9]{3,4}-)?[0-9]{7,8}$"),
          Validators.maxLength(20),
        ],],
        "roleId": [this.currentEntity.sysProfile.roleId, [
          Validators.required,
          Validators.pattern("[0-9]{1,20}"),
          Validators.maxLength(20),
        ],],
        "companyId": [this.currentEntity.sysProfile.companyId, [
          Validators.required,
        ],],
        "sex": [this.currentEntity.sysProfile.sex, [
          Validators.required,
        ],],


      }),
      "confirmPassword": [],

    }
    this.formGroup = this.fromBuider.group(obj);

  }


  /**
   * 设置表单错误对象
   * 
   * @memberof UserEditComponent
   */
  setFormError(): void {
    this.formErrors = {
      'unEnabled': '',
      'userName': '',
      'realName': '',
      'email': '',
      'telNo': '',
      'faxNo': '',
      'passWord': '',
      'roleId': '',
      'companyId': '',
      'sex': '',
    };

  }


  /**
   * 设置表单验证信息
   * 
   * @memberof UserEditComponent
   */
  setValidationMessages(): void {
    this.validationMessages = {
      'unEnabled': {
        'required': '是否启用不能为空',
      },
      'userName': {
        'required': '用户名不能为空。',
        'pattern': '用户名必须由字母数字下划线组成。',
        'maxlength': '用户名不能多于50个字符长度。',
        'exist': '用户名已存在。',
      },
      'realName': {
        'required': '用户姓名不能为空。',
        'pattern': '用户姓名由汉字组成。',
        'maxlength': '用户姓名不能多于50个字符长度。',
        'exist': '用户姓名已存在。',
      },
      'email': {
        'required': '电子邮箱不能为空。',
        'maxlength': '电子邮箱不能多于20个字符长度。',
        'pattern': '电子邮箱由字母、数字、-、@符号组成。',
        'exist': '电子邮箱已存在',
      },
      'telNo': {
        'required': '联系电话不能为空。',
        'maxlength': '联系电话不能多于11个字符长度。',
        'pattern': '电话号码不正确。',
        'exist': '电话已存在',
      },
      'faxNo': {
        'required': '传真不能为空。',
        'maxlength': '传真不能多于20个字符长度。',
        'pattern': '传真由数字、-组成。',
        'exist': '传真已存在',
      },
      'passWord': {
        'required': '密码不能为空。',
        'maxlength': '密码不能多于50个字符长度。',
      },
      'roleId': {
        'required': '角色不能为空。',
      },
      'companyId': {
        'required': '不能为空。',
      },
      'sex': {
        'required': '不能为空。',
      },
    };

  }


  /**
   * 异步校验userName是否存在
   */
  userNameAsnyValidator(control: FormControl): any {
    if (!control.value || control.value == this.currentEntity.sysUser.userName) {
      return Observable.of(null);
    }
    return this.userService.hasUserName(control.value, this.currentEntity.sysUser.userId)
      .map(res => res ? { exist: true } : null);
  }
  /**
   * 新建
   * 
   * @memberof UserEditComponent
   */

  onCreate() {
    if (!this.hasError()) {
      if (this.file) {
        this.factoryService.upFile(this.file)
          .then(res => {
            this.changeCurrent(res);
            this.onSaveCreate()
          })
          .catch(err => {
            console.log(err)
          })
      } else {
        this.changeCurrent();
        this.onSaveCreate()
      }

    }
  }

  onSaveCreate() {
    if (!this.hasError()) {
      this.userService.create(this.currentEntity)
        .then(res => {
          (this.parentBlade.bladeContainerInstance).refresh(res);
          this.bladeService.closeBlade(this.currentBlade);
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }

  }

  /**
   *  更新
   * 
   * @returns {(any | Promise<any> | Observable<any>)} 
   * @memberof UserEditComponent
   */
  saveChange(): any | Promise<any> | Observable<any> {
    if (this.canSaveChange(this.currentBlade)) {
      if (this.file) {
        this.factoryService.upFile(this.file)
          .then(res => {
            if (res) {
              let currentUserProfile = JSON.parse(window.sessionStorage.getItem('currentUserProfile'));
            // currentUserProfile.icon = res;
            currentUserProfile.icon = res;
            window.sessionStorage.setItem('currentUserProfile', JSON.stringify(currentUserProfile))
      
              this.changeCurrent(currentUserProfile.icon)
              this.onSave()
            }
          })
      } else {
        this.changeCurrent()
        this.onSave()
      }

    }
  };
  onSave() {
    this.userService.myUpdate(this.currentEntity)
      .then(res => {
        if (res) {
          (this.parentBlade.bladeContainerInstance).refresh(res);
          this.bladeService.closeBlade(this.currentBlade);
          return true;
        }
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }
  changeCurrent(url?: string) {
    this.bladeData.isLoading = true;
    let formValue = this.formGroup.value;

    this.currentEntity.sysUser.unEnabled = formValue.sysUser.unEnabled;
    this.currentEntity.sysUser.userName = formValue.sysUser.userName;
    this.currentEntity.sysUser.passWord = formValue.sysUser.passWord;
    this.currentEntity.sysProfile.realName = formValue.sysUser.realName;

    this.currentEntity.sysProfile.email = formValue.sysProfile.email;
    this.currentEntity.sysProfile.telNo = formValue.sysProfile.telNo;
    this.currentEntity.sysProfile.faxNo = formValue.sysProfile.faxNo;
    this.currentEntity.sysProfile.roleId = formValue.sysProfile.roleId;
    this.currentEntity.sysProfile.companyId = formValue.sysProfile.companyId;
    this.currentEntity.sysProfile.sex = formValue.sysProfile.sex;
    if (url) {
      this.currentEntity.sysProfile.icon = url;
    }

    this.currentEntity.basicUserFarmList = this.userFarms;
  }



  /**
   * 选择所属风场
   * 
   * @param {boolean} check 
   * @param {Farm} farm 
   * @memberof UserEditComponent
   */
  farmIsChecked(check: boolean, farm: Farm) {
    let index = this.userFarms.findIndex(o => o.farmId == farm.farmId)
    if (check) {
      if (index < 0) {
        if (!this.isNew) {//编辑
          this.userFarms.push(new UserFarm(farm.farmId, false, this.currentEntity.sysUser.userId));
        } else {
          this.userFarms.push(new UserFarm(farm.farmId, false));
        }
      }
    } else {
      if (index > -1) {
        this.userFarms.splice(index, 1);
      }
    }
    this.hasChange();
  }


  // onblur() {
  //   this.showErrow = (this.formGroup.controls.sysUser.value.passWord == this.confirmPasswords) ? false : true;
  //   this.isDisabled=this.showErrow?true:!this.formGroup.valid;
  // }
  onkeyup() {
    this.showErrow = (this.formGroup.controls.sysUser.value.passWord == this.confirmPasswords) ? false : true;
    this.isDisabled = this.showErrow ? true : !this.formGroup.valid;
  }










  onUpload(ev) {
    this.file = ev.files;
  }

  onRemove(ev) {
    this.file = null;
  }

  sexChange(value) {
    let currentUserProfile = JSON.parse(window.sessionStorage.getItem('currentUserProfile'))
    currentUserProfile.sex = value;
    window.sessionStorage.setItem('currentUserProfile', JSON.stringify(currentUserProfile))
  }

}



// WEBPACK FOOTER //
// ./src/app/module/basic/user/user-edit/user-edit.component.ts